import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart' ;
import 'package:flutter/services.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mfkb/config/Config.dart';
import 'package:mfkb/service/DynamicService.dart';
import 'package:mfkb/util/HttpUtil.dart';
import 'package:toast/toast.dart';

class Publish extends StatefulWidget {
  @override
  _PublishState createState() => _PublishState();
}

class _PublishState extends State<Publish> {

  List<dynamic> pickImgs = [] ;
  bool show = true ;
  String content = null ;
  bool canUpload = false ;
  dynamic timer = null ;
  var _textController = TextEditingController() ;

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.dark ,
      child:WillPopScope(
        child: Scaffold(
          body: Stack(
            children: <Widget>[
              Container(
                color: Colors.white ,
                child: Column(
                  children: <Widget>[
                    Container(
                      height: MediaQuery.of(context).padding.top ,
                      color: Colors.white ,
                    ) ,
                    Container(
                      height: 45 ,
                      color: Colors.white ,
                      child: Row(
                        children: <Widget>[
                          GestureDetector(
                            child: Container(
                              width: 40 ,
                              height: 24,
                              margin: EdgeInsets.only(left:ScreenUtil().setWidth(15)),
                              child: Container(
                                width: 24,
                                margin: EdgeInsets.only(right:16),
                                child: Image.asset("assets/images/close.png" , fit: BoxFit.fill,),
                              ),
                            ),
                            onTap: (){
                              Navigator.of(context).pop() ;
                            },
                          ) ,
                          Expanded(
                            child: Container(
                              child: Center(
                                child: Text("发布动态" , style: TextStyle(
                                  fontSize: ScreenUtil().setSp(18) ,
                                  fontWeight: FontWeight.bold ,
                                  color: Color.fromARGB(255, 19, 28, 53)
                                ),),
                              ),
                            ),
                          ) ,
                          GestureDetector(
                            child: Container(
                              width: 40,
                              margin: EdgeInsets.only(right:ScreenUtil().setWidth(15)),
                              child: Text("发布" , textAlign: TextAlign.end, style: TextStyle(
                                fontSize: ScreenUtil().setSp(14) ,
                                fontWeight: FontWeight.bold ,
                                color:Color.fromARGB(255, 0, 167, 187)
                              ),),
                            ),
                            onTap: () async{
                              FocusScope.of(context).requestFocus(FocusNode()) ;
                              if(content == null || content == ""){
                                Toast.show("请填写发布内容", context) ;
                                return ;
                              }
                              setState(() {
                                canUpload = true ;
                              });
                              timer = Timer.periodic(const Duration(milliseconds: 500), (t) async {
                                print("laile") ;
                                List<String> url = [] ;
                                for(var m=0 ; m < pickImgs.length ; m++){
                                  print(m) ;
                                  if(pickImgs[m]["url"] == "error"){
                                    timer.cancel() ;
                                    setState(() {
                                        canUpload = false ;
                                    });
                                    Toast.show("图片上传失败", context) ;
                                  }
                                  if(pickImgs[m]["url"] == null || pickImgs[m]["url"] == ""){
                                    canUpload = true ;
                                    return ;
                                  }else{
                                    url.add(pickImgs[m]["url"]) ;
                                  }
                                }
                                timer.cancel() ;
                                var data = await DynamicService().publish(content, url) ;
                                setState(() {
                                    canUpload = false ;
                                });
                                print(data) ;
                                if(data["code"] == 200){
                                  Navigator.of(context).pop(data["data"]) ;
                                }else{
                                  Navigator.of(context).pop(data["data"]) ;
                                }
                              });
                            },
                          ) ,
                        ],
                      ),
                    ) ,
                    Container(
                      height: ScreenUtil().setHeight(1),
                      color: Color.fromARGB(255, 236, 237, 241),
                    ) ,
                    Container(
                      height: ScreenUtil().setHeight(175),
                      padding: EdgeInsets.only(left:ScreenUtil().setWidth(15) , right:ScreenUtil().setWidth(15) , top:ScreenUtil().setHeight(5) , bottom: ScreenUtil().setHeight(15)),
                      child: TextField(
                        maxLines: 6,
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(16) ,
                          color: Color.fromARGB(255, 121, 132, 155) ,
                        ),
                        decoration: InputDecoration(
                          hintText: "这一刻的想法" ,
                          border: InputBorder.none ,
                          hintStyle: TextStyle(
                            fontSize: ScreenUtil().setSp(16) ,
                            color: Color.fromARGB(255, 121, 132, 155) ,
                          )
                        ),
                        controller: _textController,
                        onChanged: (value){
                          content = value ;
                        },
                      ),
                    ) ,
                    Container(
                      margin: EdgeInsets.only(left:ScreenUtil().setWidth(15) , right:ScreenUtil().setWidth(14)),
                      child: Row(
                        children: <Widget>[
                          Row(
                            children:List.generate(pickImgs.length, (index){
                              return Stack(
                                children: <Widget>[
                                  Container(
                                    width: ScreenUtil().setWidth(110),
                                    height: ScreenUtil().setWidth(110),
                                    margin: EdgeInsets.only(left:index == 0 ? 0 : ScreenUtil().setWidth(8)),
                                    child:ClipRRect(
                                      borderRadius: BorderRadius.all(Radius.circular(8)),
                                      child:  Image.file(pickImgs[index]["image"] , fit: BoxFit.fill,),
                                    )
                                  ) ,
                                  Positioned(
                                    top: ScreenUtil().setWidth(3),
                                    right: ScreenUtil().setWidth(3),
                                    child: GestureDetector(
                                      child: Container(
                                        width: 24,
                                        height: 24,
                                        decoration: BoxDecoration(
                                          color: Color.fromARGB(150, 0, 0, 0) ,
                                          borderRadius: BorderRadius.all(Radius.circular(12))
                                        ),
                                        child: Image.asset("assets/images/close.png"),
                                      ),
                                      onTap: (){
                                        setState(() {
                                          pickImgs.removeAt(index) ;
                                        });
                                      },
                                    )
                                  ) ,
                                  Positioned(
                                    bottom: ScreenUtil().setHeight(5),
                                    child: Container(
                                      height: ScreenUtil().setHeight(3),
                                      width: ScreenUtil().setWidth(110),
                                      margin: EdgeInsets.only(left:ScreenUtil().setWidth(index == 0 ? 0 : ScreenUtil().setWidth(8))),
                                      child: LinearProgressIndicator(
                                        valueColor: new AlwaysStoppedAnimation<Color>(pickImgs[index]["color"]),
                                        backgroundColor: Colors.grey,
                                        value: pickImgs[index]["process"],
                                      ),
                                    ),
                                  )
                                ],
                              ) ;
                            }),
                          ) ,
                          Visibility(
                            visible: pickImgs.length == 3 ? false : true ,
                            child: GestureDetector(
                              child: Container(
                                margin: EdgeInsets.only(left:pickImgs.length == 0 ? 0 : ScreenUtil().setWidth(8)),
                                width: ScreenUtil().setWidth(110),
                                height: ScreenUtil().setWidth(110),
                                decoration: BoxDecoration(
                                  color: Color.fromARGB(255, 246, 246, 248) ,
                                  borderRadius: BorderRadius.all(Radius.circular(8)) ,
                                ),
                                child: Center(
                                  child: Image.asset("assets/images/add.png"),
                                ) ,
                              ),
                              onTap: () async{
                                var image = await ImagePicker.pickImage(source: ImageSource.gallery) ;
                                if(image == null) return ;
                                if(pickImgs.length == 2){
                                  show = false ;
                                }
                                var index = pickImgs.length ;
                                int len = image.lengthSync() ;
                                if(len > 1024*1024*9){
                                  Toast.show("文件太大", context) ;
                                  return ;
                                }
                                File img = null ;
                                print(len) ;
                                if(len >= 1024*1024*6){
                                  img = await FlutterNativeImage.compressImage(
                                    image.path ,
                                    quality: 80 ,
                                    percentage: 60
                                  ) ;
                                }else if(len > 1024*1024 && len < 1024*1024*6){
                                  img = await FlutterNativeImage.compressImage(
                                    image.path ,
                                    quality: 80 ,
                                    percentage: 80
                                  ) ;
                                }else{
                                  img = await FlutterNativeImage.compressImage(
                                    image.path ,
                                    quality: 100 ,
                                    percentage: 100
                                  ) ;
                                }
                                print(img.lengthSync()) ;
                                setState(() {
                                  _textController.text = content == null ? "" : content ;
                                  _textController.selection = TextSelection(baseOffset: content == null ? 0 : "$content".length, extentOffset: content == null ? 0 : "$content".length) ;
                                  pickImgs.add({"image":img , "process":0.0 , "color":Colors.green.withOpacity(0.6)}) ;
                                });
                                var u = await HttpUtil().upload(Config().getHost()+"/api/admin/v1/upload", img , onProcess: (value){
                                  setState(() {
                                    pickImgs[index]["process"] = value ;
                                  });
                                }) ;
                                print(u) ;
                                if(u != null && u["code"] == 200){
                                  pickImgs[index]["url"] = u["data"] ;
                                  pickImgs[index]["color"] = Colors.green ;
                                }else{
                                  pickImgs[index]["url"] = "error" ;
                                  pickImgs[index]["color"] = Colors.red ;
                                  setState(() {});
                                  Toast.show("图片上传失败", context) ;
                                }
                              },
                            ),
                          ) ,
                        ],
                      ),
                    )
                  ],
                ),
              ) ,
              Visibility(
                visible: canUpload,
                child: Container(
                  color: Color.fromARGB(160, 0, 0, 0),
                  child: Center(
                    child: Text("正在发布，请稍等..." , style: TextStyle(color: Colors.white),),
                  ),
                ),
              )
            ],
          )
        ),
        onWillPop: () async{
          if(timer != null){
            timer.cancle() ;
          }
          return true ;
        },
      )
    ) ;
  }
}